import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../constants/constants.dart';

/// 主播放页面
/// 显示当前播放音乐的详细信息和播放控制界面
class PlayerScreen extends StatefulWidget {
  final bool autoPlay;
  
  const PlayerScreen({super.key, this.autoPlay = false});

  @override
  State<PlayerScreen> createState() => _PlayerScreenState();
}

class _PlayerScreenState extends State<PlayerScreen>
    with TickerProviderStateMixin {
  late AnimationController _rotationController;
  late AnimationController _glowController;
  late AnimationController _slideController;
  late AnimationController _fadeController;
  late Animation<double> _rotationAnimation;
  late Animation<double> _glowAnimation;
  late Animation<Offset> _slideAnimation;
  late Animation<double> _fadeAnimation;

  bool _isDraggingProgress = false;
  double _dragProgressValue = 0.0;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  /// 初始化动画控制器
  void _initAnimations() {
    // 旋转动画控制器
    _rotationController = AnimationController(
      duration: const Duration(seconds: 20),
      vsync: this,
    );
    _rotationAnimation = Tween<double>(
      begin: 0,
      end: 1,
    ).animate(_rotationController);

    // 光效动画控制器
    _glowController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );
    _glowAnimation = Tween<double>(
      begin: 0.5,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _glowController,
      curve: Curves.easeInOut,
    ));

    // 滑入动画控制器
    _slideController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _slideController,
      curve: Curves.easeOutCubic,
    ));

    // 淡入动画控制器
    _fadeController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeIn,
    ));

    // 循环播放光效动画
    _glowController.repeat(reverse: true);

    // 启动加载和动画
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _startLoadingAndAnimations();
    });
  }

  /// 开始加载和动画
  void _startLoadingAndAnimations() {
    // 启动入场动画
    _slideController.forward();
    _fadeController.forward();
    
    // 启动旋转动画（用于加载状态）
    _rotationController.repeat();
    
    // 如果有音乐且设置了自动播放，则开始播放
    final audioService = Provider.of<AudioPlayerService>(context, listen: false);
    if (audioService.currentMusic != null && widget.autoPlay) {
      audioService.resume();
    } else if (audioService.currentMusic == null &&
        audioService.playlist.isNotEmpty) {
      audioService.playMusic(audioService.playlist.first);
    }
  }

  @override
  void dispose() {
    _rotationController.dispose();
    _glowController.dispose();
    _slideController.dispose();
    _fadeController.dispose();
    super.dispose();
  }

  String formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);

    if (hours > 0) {
      return '${twoDigits(hours)}:${twoDigits(minutes)}:${twoDigits(seconds)}';
    } else {
      return '${twoDigits(minutes)}:${twoDigits(seconds)}';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: AppTheme.backgroundGradientDark,
        ),
        child: SafeArea(
          child: Consumer<AudioPlayerService>(
            builder: (context, audioService, child) {
              final currentMusic = audioService.currentMusic;

              // 根据播放状态控制旋转动画
              if (audioService.isPlaying && !audioService.isLoading) {
                _rotationController.repeat();
              } else {
                _rotationController.stop();
              }

              return GestureDetector(
                onVerticalDragEnd: audioService.isLoading ? null : (details) {
                  if (details.primaryVelocity != null) {
                    if (details.primaryVelocity! > 200) {
                      // 向下拖动 - 下一首
                      audioService.playNext();
                    } else if (details.primaryVelocity! < -200) {
                      // 向上拖动 - 上一首
                      audioService.playPrevious();
                    }
                  }
                },
                child: Column(
                  children: [
                    // 顶部导航栏
                    _buildAppBar(context),

                    // 主要内容区域
                    Expanded(
                      child: currentMusic != null
                          ? _buildPlayerContent(
                              context, audioService, currentMusic)
                          : _buildEmptyState(context),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildAppBar(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(AppTheme.spacingMedium),
      child: Row(
        children: [
          IconButton(
            onPressed: () => Navigator.of(context).pop(),
            icon: const Icon(
              Icons.keyboard_arrow_down,
              size: AppTheme.iconSizeLarge,
              color: AppTheme.textPrimaryDark,
            ),
          ),
          const Expanded(
            child: Text(
              '正在播放',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: AppTheme.fontSizeLarge,
                fontWeight: FontWeight.w600,
                color: AppTheme.textPrimaryDark,
              ),
            ),
          ),
          IconButton(
            onPressed: () {
              // TODO: 显示更多选项菜单
            },
            icon: const Icon(
              Icons.more_vert,
              size: AppTheme.iconSizeLarge,
              color: AppTheme.textPrimaryDark,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建播放器主要内容
  Widget _buildPlayerContent(BuildContext context, AudioPlayerService audioService, Music music) {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: SlideTransition(
        position: _slideAnimation,
        child: Padding(
          padding: const EdgeInsets.all(AppTheme.spacingLarge),
          child: Column(
            children: [
              // 专辑封面
              Expanded(
                flex: 3,
                child: _buildAlbumCover(music, audioService.isPlaying),
              ),
              
              const SizedBox(height: AppTheme.spacingXL),
              
              // 音乐信息
              _buildMusicInfo(music),
              
              const SizedBox(height: AppTheme.spacingXL),
              
              // 进度条
              _buildProgressBar(audioService),
              
              const SizedBox(height: AppTheme.spacingXL),
              
              // 播放控制
              _buildPlayControls(audioService, audioService.playlist.length),
              
              const SizedBox(height: AppTheme.spacingLarge),
              
              // 音量控制
              _buildVolumeControls(audioService),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建专辑封面
  Widget _buildAlbumCover(Music music, bool isPlaying) {
    return Center(
      child: AnimatedBuilder(
        animation: _glowAnimation,
        builder: (context, child) {
          return Container(
            width: AppTheme.albumCoverSizeXXL,
            height: AppTheme.albumCoverSizeXXL,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              boxShadow: isPlaying
                  ? [
                      BoxShadow(
                        color: AppTheme.primaryColor
                            .withOpacity(_glowAnimation.value * 0.6),
                        blurRadius: 30 * _glowAnimation.value,
                        spreadRadius: 10 * _glowAnimation.value,
                      ),
                    ]
                  : null,
            ),
            child: RotationTransition(
              turns: _rotationAnimation,
              child: Container(
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  gradient: LinearGradient(
                    colors: [
                      AppTheme.primaryColor,
                      AppTheme.secondaryColor,
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  boxShadow: AppTheme.elevatedShadow,
                ),
                child: ClipOval(
                  child: music.coverArt != null
                      ? Image.asset(
                          music.coverArt!,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) {
                            return _buildDefaultCover();
                          },
                        )
                      : _buildDefaultCover(),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建默认封面
  Widget _buildDefaultCover() {
    return Container(
      decoration: const BoxDecoration(
        gradient: AppTheme.primaryGradient,
      ),
      child: const Center(
        child: Icon(
          Icons.music_note,
          size: AppTheme.iconSizeXXL,
          color: Colors.white,
        ),
      ),
    );
  }

  /// 构建音乐信息
  Widget _buildMusicInfo(Music music) {
    return Column(
      children: [
        Text(
          music.title,
          style: const TextStyle(
            fontSize: AppTheme.fontSizeXL,
            fontWeight: FontWeight.bold,
            color: AppTheme.textPrimaryDark,
          ),
          textAlign: TextAlign.center,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
        ),
        const SizedBox(height: AppTheme.spacingSmall),
        Text(
          music.artist,
          style: const TextStyle(
            fontSize: AppTheme.fontSizeMedium,
            color: AppTheme.textSecondaryDark,
          ),
          textAlign: TextAlign.center,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        if (music.album != null) ...[
          const SizedBox(height: AppTheme.spacingXS),
          Text(
            music.album!,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeSmall,
              color: AppTheme.textHintDark,
            ),
            textAlign: TextAlign.center,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ],
    );
  }

  /// 构建进度条
  Widget _buildProgressBar(AudioPlayerService audioService) {
    return Column(
      children: [
        SliderTheme(
          data: SliderTheme.of(context).copyWith(
            trackHeight: AppTheme.progressBarHeightLarge,
            thumbShape: const RoundSliderThumbShape(
              enabledThumbRadius: 8,
            ),
            overlayShape: const RoundSliderOverlayShape(
              overlayRadius: 16,
            ),
            activeTrackColor: AppTheme.primaryColor,
            inactiveTrackColor: AppTheme.primaryColor.withOpacity(0.3),
            thumbColor: AppTheme.primaryColor,
            overlayColor: AppTheme.primaryColor.withOpacity(0.2),
          ),
          child: Slider(
            value: _isDraggingProgress
                ? _dragProgressValue
                : audioService.currentPosition.inMilliseconds.toDouble(),
            min: 0.0,
            max: audioService.totalDuration.inMilliseconds > 0
                ? audioService.totalDuration.inMilliseconds.toDouble()
                : 1.0,
            onChanged: audioService.isLoading
                ? null
                : (value) {
                    setState(() {
                      _isDraggingProgress = true;
                      _dragProgressValue = value;
                    });
                  },
            onChangeStart: audioService.isLoading
                ? null
                : (value) {
                    setState(() {
                      _isDraggingProgress = true;
                      _dragProgressValue = value;
                    });
                  },
            onChangeEnd: audioService.isLoading
                ? null
                : (value) {
                    audioService.seekTo(Duration(milliseconds: value.round()));
                    setState(() {
                      _isDraggingProgress = false;
                    });
                  },
          ),
        ),
        Padding(
          padding:
              const EdgeInsets.symmetric(horizontal: AppTheme.spacingMedium),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                _isDraggingProgress
                    ? formatDuration(
                        Duration(milliseconds: _dragProgressValue.round()))
                    : audioService.currentPositionText,
                style: const TextStyle(
                    color: AppTheme.textSecondaryDark,
                    fontSize: AppTheme.fontSizeSmall),
              ),
              Text(
                audioService.totalDurationText,
                style: const TextStyle(
                    color: AppTheme.textSecondaryDark,
                    fontSize: AppTheme.fontSizeSmall),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建播放控制按钮
  Widget _buildPlayControls(AudioPlayerService audioService, int playlistCount) {
    final isSingleSong = playlistCount <= 1;

    Widget buildPlayPauseButton() {
      final containerSize = isSingleSong
          ? AppTheme.playerControlSizeLarge + 20
          : AppTheme.playerControlSizeLarge;
      final iconSize =
          isSingleSong ? AppTheme.iconSizeXL + 8 : AppTheme.iconSizeXL;

      return AnimatedScale(
        scale: audioService.isPlaying && !audioService.isLoading ? 1.1 : 1.0,
        duration: const Duration(milliseconds: 200),
        child: Container(
          width: containerSize,
          height: containerSize,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            gradient: AppTheme.primaryGradient,
            boxShadow: [
              BoxShadow(
                color: AppTheme.primaryColor.withOpacity(0.4),
                blurRadius: 20,
                spreadRadius: 5,
              ),
            ],
          ),
          child: Center(
                    child: audioService.isLoading
                        ? Padding(
                            padding: EdgeInsets.all(isSingleSong ? 16.0 : 12.0),
                            child: AnimatedBuilder(
                              animation: _rotationController,
                              builder: (context, child) {
                                return Transform.rotate(
                                  angle: _rotationController.value * 2 * 3.14159,
                                  child: Icon(
                                    Icons.music_note,
                                    size: iconSize,
                                    color: Colors.white,
                                  ),
                                );
                              },
                            ),
                          )
                        : IconButton(
                            onPressed: audioService.isLoading ? null : () {
                              if (audioService.isPlaying) {
                                audioService.pause();
                              } else {
                                audioService.resume();
                              }
                            },
                            icon: AnimatedSwitcher(
                              duration: const Duration(milliseconds: 200),
                              child: Icon(
                                audioService.isPlaying ? Icons.pause : Icons.play_arrow,
                                key: ValueKey(audioService.isPlaying),
                                size: iconSize,
                                color: Colors.white,
                              ),
                            ),
                          ),
          ),
        ),
      );
    }

    if (isSingleSong) {
      // 只有一首歌时，只显示播放按钮
      return Center(child: buildPlayPauseButton());
    }

    // 多首歌时显示完整控制
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        // 随机播放
        AnimatedScale(
          scale: audioService.isShuffleEnabled ? 1.1 : 1.0,
          duration: const Duration(milliseconds: 200),
          child: IconButton(
            onPressed: audioService.isLoading
                ? null
                : () => audioService.toggleShuffle(),
            icon: Icon(
              Icons.shuffle,
              color: audioService.isShuffleEnabled
                  ? AppTheme.primaryColor
                  : AppTheme.textSecondaryDark,
              size: AppTheme.iconSizeLarge,
            ),
          ),
        ),

        // 上一首
        AnimatedOpacity(
          opacity: audioService.hasPrevious ? 1.0 : 0.5,
          duration: const Duration(milliseconds: 200),
          child: IconButton(
            onPressed: audioService.isLoading || !audioService.hasPrevious
                ? null
                : audioService.playPrevious,
            icon: const Icon(
              Icons.skip_previous,
              size: AppTheme.iconSizeXL,
              color: AppTheme.textPrimaryDark,
            ),
          ),
        ),

        // 播放/暂停
        buildPlayPauseButton(),

        // 下一首
        AnimatedOpacity(
          opacity: audioService.hasNext ? 1.0 : 0.5,
          duration: const Duration(milliseconds: 200),
          child: IconButton(
            onPressed: audioService.isLoading || !audioService.hasNext
                ? null
                : audioService.playNext,
            icon: const Icon(
              Icons.skip_next,
              size: AppTheme.iconSizeXL,
              color: AppTheme.textPrimaryDark,
            ),
          ),
        ),

        // 循环模式
        AnimatedScale(
          scale: audioService.playMode != PlayMode.sequence ? 1.1 : 1.0,
          duration: const Duration(milliseconds: 200),
          child: IconButton(
            onPressed:
                audioService.isLoading ? null : () => audioService.setPlayMode(audioService.playMode.next),
            icon: Icon(
              audioService.playMode == PlayMode.repeatOne
                  ? Icons.repeat_one
                  : audioService.playMode == PlayMode.repeatAll ? Icons.repeat : Icons.shuffle,
              color: audioService.playMode != PlayMode.sequence
                  ? AppTheme.primaryColor
                  : AppTheme.textSecondaryDark,
              size: AppTheme.iconSizeLarge,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建音量和其他控制
  Widget _buildVolumeControls(AudioPlayerService audioService) {
    return Row(
      children: [
        const Icon(
          Icons.volume_down,
          color: AppTheme.textSecondaryDark,
          size: AppTheme.iconSizeMedium,
        ),
        Expanded(
          child: SliderTheme(
            data: SliderTheme.of(context).copyWith(
              trackHeight: AppTheme.progressBarHeight,
              thumbShape: const RoundSliderThumbShape(
                enabledThumbRadius: 6,
              ),
              overlayShape: const RoundSliderOverlayShape(
                overlayRadius: 12,
              ),
            ),
            child: Slider(
              value: audioService.volume,
              onChanged: (value) => audioService.setVolume(value),
              activeColor: AppTheme.primaryColor,
              inactiveColor: AppTheme.primaryColor.withOpacity(0.3),
            ),
          ),
        ),
        const Icon(
          Icons.volume_up,
          color: AppTheme.textSecondaryDark,
          size: AppTheme.iconSizeMedium,
        ),
      ],
    );
  }

  /// 构建空状态
  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: AppTheme.albumCoverSizeLarge,
            height: AppTheme.albumCoverSizeLarge,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: AppTheme.surfaceDark,
              border: Border.all(
                color: AppTheme.primaryColor.withOpacity(0.3),
                width: 2,
              ),
            ),
            child: const Icon(
              Icons.music_note,
              size: AppTheme.iconSizeXL,
              color: AppTheme.textHintDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingLarge),
          const Text(
            '暂无播放音乐',
            style: TextStyle(
              fontSize: AppTheme.fontSizeLarge,
              color: AppTheme.textSecondaryDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingMedium),
          const Text(
            '选择一首音乐开始播放',
            style: TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textHintDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingXL),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: const Text('浏览音乐库'),
          ),
        ],
      ),
    );
  }
}
